"""The base Controller API

Provides the BaseController class for subclassing, and other objects
utilized by Controllers.
"""
from paste.request import construct_url
from paste.httpexceptions import HTTPMovedPermanently

from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.controllers.util import abort, etag_cache, redirect_to
from pylons.decorators import jsonify, validate
from pylons.i18n import _, ungettext, N_
from pylons.templating import render
from pylons.templating import pylons_globals

import cibynet.lib.helpers as h
from cibynet.model import meta
from cibynet.model.all_objects import *
from cibynet.lib.auth import authorisation


class BaseController(WSGIController):

  def __call__(self, environ, start_response):
    """Invoke the Controller"""
    # WSGIController.__call__ dispatches to the Controller method
    # the request is routed to. This routing information is
    # available in environ['pylons.routes_dict']
    
    # We want all of our URLs finishing by '/'
    # for indexing reasons as well as the ease it gives us to put relative
    # links in every page.
    if not environ['PATH_INFO'].endswith('/'):
      environ['PATH_INFO'] += '/'
      url = construct_url(environ)
      raise HTTPMovedPermanently(url)
    try:
      return WSGIController.__call__(self, environ, start_response)
    finally:
      meta.Session.remove()
      
  def __before__(self):
    """Set the indicator self.ajax_request to True or False.
    """
    self.ajax_request = request.GET.get("ajax") == "true" or \
                        request.POST.get("_ajax") == "true"
      

class AdminController(BaseController):
  """Just check that the logged in user is admin.
  """
  
  def __before__(self):
    authorisation.UserInGroup('admin')
    BaseController.__before__(self)


def get_template(template_name):
  """Returns a template object corresponding to the given name.
  """
  globs = pylons_globals()
  return globs['app_globals'].mako_lookup.get_template(template_name)


def render_def(template_name, name, **kwargs):
  """Render a def in a mako template.
  Taken from http://techspot.zzzeek.org/?p=29
  """
  globs = pylons_globals()
  if kwargs:
    globs = globs.copy()
    globs.update(kwargs)
  template = globs['app_globals'].mako_lookup.get_template(template_name)
  template_def = template.get_def(name)
  return template_def.render(**globs)
  

# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
           or __name == '_']
